package com.synv.flashcard;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.nodes.Document;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.synv.entity.Category;
import com.synv.entity.FlashCard;
import com.synv.flashcard.R.color;
import com.synv.util.DataBaseHelper;
import com.synv.util.Utils;
import com.synv.util.WebParserUtils;
import com.synv.util.WordListAdapter;

public class CategoryDetailActivity extends Activity {

	private RelativeLayout rlViewCategory;
	private RelativeLayout rlSaveCategory;
	private Button btnEditCategory, btnSaveCategory, btnAddWord, btnDeleteList;
	private TextView txtCategoryName;
	private EditText txtEditName, txtNewWord;
	private Integer categorySeq;
	private String categoryName;
	private ListView listView;
	private WordListAdapter adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_category_detail);
		Intent intent = getIntent();
		categorySeq = intent.getIntExtra("categorySeq", 1);
		categoryName = intent.getStringExtra("categoryName");
		if(categoryName == null) categoryName = "";
		
		ActionBar actionBar = getActionBar();
		actionBar.setBackgroundDrawable(new ColorDrawable(color.header));
		actionBar.setTitle("Edit List");
		
		txtCategoryName = (TextView) findViewById(R.id.txtCategoryName);
		txtEditName = (EditText) findViewById(R.id.txtEditName);
		txtNewWord = (EditText) findViewById(R.id.txtNewWord);
		txtCategoryName.setText(categoryName);
		txtEditName.setText(categoryName);
		
		btnAddWord = (Button) findViewById(R.id.btnAddWord);
		btnDeleteList = (Button) findViewById(R.id.btnDeleteList);
		btnEditCategory = (Button) findViewById(R.id.btnEditCategory);
		btnSaveCategory = (Button) findViewById(R.id.btnSaveCategory);
		rlViewCategory = (RelativeLayout) findViewById(R.id.rlViewCategory);
		rlSaveCategory = (RelativeLayout) findViewById(R.id.rlSaveCategory);
		listView = (ListView)findViewById(R.id.list_word);
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent contentScreen = new Intent(getApplicationContext(), WordDetailActivity.class);
				FlashCard flashcard = (FlashCard) parent.getItemAtPosition(position);
				contentScreen.putExtra("word", flashcard.getWord());
				startActivity(contentScreen);
			}
        });
		btnEditCategory.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				rlSaveCategory.setVisibility(RelativeLayout.VISIBLE);
				txtEditName.requestFocus();
				txtEditName.setSelection(categoryName.length());
				rlViewCategory.setVisibility(RelativeLayout.GONE);
			}
		});
		
		btnSaveCategory.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				saveCategory();
			}
		});
		
		btnDeleteList.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				AlertDialog.Builder alertDialog = new AlertDialog.Builder(CategoryDetailActivity.this);
				 
		        // Setting Dialog Title
		        alertDialog.setTitle("Xóa danh sách...");
		 
		        // Setting Dialog Message
		        alertDialog.setMessage("Bạn có muốn xóa danh sách này?");
		 
		        // Setting Icon to Dialog
		        alertDialog.setIcon(R.drawable.delete);
		 
		        // Setting Positive "Yes" Button
		        alertDialog.setPositiveButton("Có", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog,int which) {
		 
		            // Write your code here to invoke YES event
		            //Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
		            delete();
		            }
		        });
		 
		        // Setting Negative "NO" Button
		        alertDialog.setNegativeButton("Không", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		            // Write your code here to invoke NO event
		            //Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
		            dialog.cancel();
		            }
		        });
		 
		        // Showing Alert Message
		        alertDialog.show();
			}
		});
		
		btnAddWord.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				addNewWord(txtNewWord.getText().toString().trim(), v.getContext());
			}
		});
		
		if(categorySeq == Category.MARKED_CATEGORY) {
			RelativeLayout rlDeteteCategory = (RelativeLayout)findViewById(R.id.rlDeleteList);
			RelativeLayout rlEditCategory = (RelativeLayout)findViewById(R.id.rlEditCategory);
			rlDeteteCategory.setVisibility(View.GONE);
			rlEditCategory.setVisibility(View.GONE);
		}
		init();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.category_detail, menu);
		return true;
	}

	private void init() {
		DataBaseHelper myDbHelper = new DataBaseHelper(this);
		Cursor c = myDbHelper.getReadableDatabase().query("flashcard", null, "Category like '%," + categorySeq + ",%'", null, null, null, "word");
		if(categorySeq == Category.MARKED_CATEGORY) {
			c.close();
			c = myDbHelper.getReadableDatabase().query("flashcard", null, "Bookmark = 1", null, null, null, "word");
		}
 		c.moveToFirst();
 		List<FlashCard> flashcards = new ArrayList<FlashCard>();
 		while(!c.isAfterLast()) {
 			FlashCard flashcard = new FlashCard(c.getInt(0), c.getString(1), 
 					c.getInt(2), c.getString(3), c.getString(4), 
 					c.getString(5), c.getString(6), c.getString(7), 
 					c.getInt(8), c.getInt(9), c.getInt(10), c.getString(11));
 			flashcards.add(flashcard);
 			c.moveToNext();
 		}
 		c.close();
 		myDbHelper.close();
 		
 		adapter = new WordListAdapter(this, R.layout.word_item_row, flashcards);
 		adapter.setCategorySeq(categorySeq);
		listView.setAdapter(adapter);
		txtNewWord.clearFocus();
		listView.requestFocus();
		txtNewWord.setText("");
		InputMethodManager imm = (InputMethodManager)getSystemService(
			      Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(txtNewWord.getWindowToken(), 0);
	}
	
	private void delete() {
		DataBaseHelper myDbHelper = new DataBaseHelper(this);
		myDbHelper.getWritableDatabase().delete("Category", "Seq=" + categorySeq, null);
		myDbHelper.close();
		finish();
	}
	
	private void saveCategory() {
		categoryName = txtEditName.getText().toString().trim();
		if("".equals(categoryName)) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Bạn phải nhập tên danh sách!")
			       .setCancelable(false)
			       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                //do things
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
			return;
		}
		rlSaveCategory.setVisibility(RelativeLayout.GONE);
		rlViewCategory.setVisibility(RelativeLayout.VISIBLE);
		txtCategoryName.setText(categoryName);
		DataBaseHelper myDbHelper = new DataBaseHelper(getApplicationContext());
		myDbHelper.getWritableDatabase().execSQL("UPDATE category SET name = '" + categoryName.replaceAll("'", "''") + "' WHERE Seq = " + categorySeq);
		myDbHelper.close();
	}
	
	private void addNewWord(String word, Context ctx) {
		try {
			listView.requestFocus();
			InputMethodManager imm = (InputMethodManager)getSystemService(
				      Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(txtNewWord.getWindowToken(), 0);
			if(word == null || "".equals(word)) {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage("Bạn phải nhập từ!")
				       .setCancelable(false)
				       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                //do things
				           }
				       });
				AlertDialog alert = builder.create();
				alert.show();
				return;
			}
			
			DataBaseHelper myDbHelper = new DataBaseHelper(this);
			Cursor c = myDbHelper.getReadableDatabase().query("flashcard", null, "Word = '" + word + "'", null, null, null, "seq");
			if(c.moveToFirst()) {
				Integer seq = c.getInt(0);
				String category = c.getString(11);
				if(category == null || category.length() == 0) category = ",";
				if(categorySeq == Category.MARKED_CATEGORY) {
					myDbHelper.getWritableDatabase().execSQL("UPDATE flashcard SET Bookmark = 1 WHERE seq=" + seq);
				} else if(!category.contains("," + categorySeq + ",")) {
					category += categorySeq + ",";
					myDbHelper.getWritableDatabase().execSQL("UPDATE flashcard SET category = '" + category + "' WHERE seq=" + seq);
				}
			} else {
				try {
					if(!Utils.checkInternetConnection(ctx)) {
		    			AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
		    			builder.setMessage("Không có kết nối Internet!")
		    			       .setCancelable(false)
		    			       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		    			           public void onClick(DialogInterface dialog, int id) {
		    			                //do things
		    			           }
		    			       });
		    			AlertDialog alert = builder.create();
		    			alert.show();
		    			return;
		    		}
					
					Document doc = WebParserUtils.getDocument(word);
					String category = "," + categorySeq + ",";
					if(categorySeq == Category.MARKED_CATEGORY) {
						myDbHelper.getWritableDatabase().execSQL("INSERT INTO flashcard (word, phonetic, meaning, wordtype, Bookmark) VALUES ('" + word + "', '" + WebParserUtils.getPhonetic(doc).replaceAll("'", "''") + "', '" + WebParserUtils.getMeaning(doc) +"', '" + WebParserUtils.getWordType(doc) + "',1)");
					} else {
						myDbHelper.getWritableDatabase().execSQL("INSERT INTO flashcard (word, phonetic, meaning, wordtype, category) VALUES ('" + word + "', '" + WebParserUtils.getPhonetic(doc).replaceAll("'", "''") + "', '" + WebParserUtils.getMeaning(doc) +"', '" + WebParserUtils.getWordType(doc) + "', '" + category + "')");
					}
					Toast.makeText(this, "Thêm từ  thành công", Toast.LENGTH_SHORT).show();
				} catch (Exception ex) {
					String category = "," + categorySeq + ",";
					if(categorySeq == Category.MARKED_CATEGORY) {
						myDbHelper.getWritableDatabase().execSQL("INSERT INTO flashcard (word, phonetic, meaning, wordtype, bookmark) VALUES ('" + word + "', null, null, null, 1)");
					} else {
						myDbHelper.getWritableDatabase().execSQL("INSERT INTO flashcard (word, phonetic, meaning, wordtype, category) VALUES ('" + word + "', null, null, null, '" + category + "')");
					}
					Toast.makeText(this, "Thêm từ thành công", Toast.LENGTH_SHORT).show();
				}
			}
			
			myDbHelper.close();
			init();
			
		} catch (Exception ex) {
			Toast.makeText(this, "ERROR", Toast.LENGTH_SHORT).show();
		}
		
	}
}
